// Copyright Leonid Shlyapnikov 2010
// Distributed under the GNU Lesser General Public License http://www.gnu.org/licenses/lgpl.html
//    author: Leonid Shlyapnikov, created on: Jul 11, 2010

#include "./ChecksumConverter.h"

#include <boost/lexical_cast.hpp>
#include <boost/exception/all.hpp>
#include <stdexcept>
#include <sstream>
#include <string>

#include "./log.h"

namespace fixparser {

ChecksumConverter::ChecksumConverter() {
    LOG_DEBUG("initializing ChecksumConverter");

    for (int indx = 0; indx < CHECKSUM_BASE; indx++) {
        std::string& str = this->checksumToStringMap_[indx];
        str = get_padding_zeros(indx);
        str += boost::lexical_cast<std::string>(indx);
    }
}

ChecksumConverter::~ChecksumConverter() {
}

const char*
ChecksumConverter::get_padding_zeros(int checksumBase256) const {
    if (0 <= checksumBase256 && checksumBase256 <= 9) {
        return "00";
    } else if (10 <= checksumBase256 && checksumBase256 <= 99) {
        return "0";
    } else if (100 <= checksumBase256 && checksumBase256 < CHECKSUM_BASE) {
        return "";
    } else {
        std::stringstream error;
        error << "Illegal value of checksumBase256: " << checksumBase256 << ", FIX checksum value must be in the interval: (0, 255]";
        BOOST_THROW_EXCEPTION(std::invalid_argument(error.str()));
    }
}

}
